package root.electronclass.electronclass.common.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 *
 * @author Lokiy
 * @date 2023/1/8 11:12
 */
open class ViewBindingFragment<T : ViewBinding> : BaseFragment() {

    private val bindingClass by lazy {
        var genericSuperclass = this::class.java.genericSuperclass
        if (genericSuperclass !is ParameterizedType && genericSuperclass is Class<*>) {
            genericSuperclass = (genericSuperclass as Class<*>).genericSuperclass
        }
        (genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<*>
    }
    private val inflateMethod by lazy { bindingClass.getDeclaredMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java) }
    private lateinit var _binding: T
    protected val binding: T get() = _binding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        @Suppress("UNCHECKED_CAST")
        return (inflateMethod.invoke(this, layoutInflater, container, false) as T).also { _binding = it }.root
    }

    companion object {
        const val EXTRA_DATA = "_DATA"
    }
    fun dp2px(value: Float) = value
}